package com.gking.processHarvest.utils;

import com.gking.processHarvest.common.BaseContext;
import com.gking.processHarvest.entity.Uploads;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.UUID;

/**
 * 上传文件
 */
@Slf4j
public class UploadFile {


    /**
     * 上传文件
     *
     * @param file     传递过来的文件数据
     * @param savePath 保存到服务器中的具体路径
     * @return s
     */
    public Uploads uploadFile(MultipartFile file, String savePath) {


        String originalFilename = file.getOriginalFilename();
        String contentType = file.getContentType();
        long size = file.getSize();
        log.info("上传的文件的原始名称为：{}", originalFilename);
        log.info("上传的文件的类型为：{}", contentType);
        log.info("上传的文件的大小为：{}", size);



        assert originalFilename != null;
        String[] hz = originalFilename.split("\\.");
        log.info("长度：{}", hz.length);
        log.info("后缀：{}", hz[hz.length - 1]);

        try {
            String fileName = UUID.randomUUID().toString() + "." + hz[hz.length - 1];
            //获取服务器根路径
            String rootPath = System.getProperty("user.dir");
            Path filePath = Paths.get(rootPath + savePath + fileName);

            Files.copy(file.getInputStream(), filePath, StandardCopyOption.REPLACE_EXISTING);

            Uploads uploads = new Uploads();
            uploads.setFilename(fileName);
            uploads.setOriginName(originalFilename);
            uploads.setMasterId(BaseContext.getCurrentId());
            uploads.setType(contentType);
            uploads.setPath(savePath + fileName);
            uploads.setSize(String.valueOf(size));

            return uploads;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }


}
